package com.s63.modules.token;

import com.baomidou.mybatisplus.core.toolkit.AES;
import com.s63.entity.User;
import com.s63.modules.security.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.Base64UrlCodec;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class JwtTokenService implements ITokenService{
    @Override
    public Token createToken(LoginUser user) {
        String token = JwtUtils.createToken(user);
        return new Token(token, user.getUser().getNickName());
    }

    @Override
    public boolean removeToken(String token) {
        throw new RuntimeException("方法没有实现");
    }

    @Override
    public LoginUser getLoginUser(String token) {
        return JwtUtils.getLoginUser(token);
    }

    public static void main(String[] args) {
        String userId = "1";
        String roleKeyList = "emp,admin";
        String permsList = "user:list,user:add";
        String data = String.join("#", userId, roleKeyList, permsList);
//        String data = userId + "#" + roleKeyList + "#" + permsList;
        System.out.println("data = " + data);
        List<String> list = new ArrayList<>();
        list.add("user");
        list.add("manager");

        String data1 = list.stream().collect(Collectors.joining(","));
        System.out.println("data1 = " + data1);
        List<String> list2 = Arrays.stream(data1.split(",")).collect(Collectors.toList());
        System.out.println("list2 = " + list2);

    }
    private static class JwtUtils {
        private static final String secret = "a*#fFaZx0xF*!~&8";
        private static final String PAYLOAD_KEY = "payload";
        public static String createToken(LoginUser loginUser) {
            String rawData = String.join("#", loginUser.getUser().getUserId() + "",
                    loginUser.getRoleKeyList().stream().collect(Collectors.joining(",")),
                    loginUser.getPermsList().stream().collect(Collectors.joining(",")));
            Map<String, Object> payload = new HashMap<>();
            payload.put(PAYLOAD_KEY, encrypt(rawData));
            return Jwts.builder()
                    .setIssuedAt(new Date())
                    .setExpiration(new Date(System.currentTimeMillis() + 15 *60*1000))
                    .setClaims(payload)
                    .signWith(SignatureAlgorithm.HS256, Base64UrlCodec.BASE64URL.encode(secret))
                    .compact();
        }

        private static Object encrypt(String rawData) {
            return AES.encrypt(rawData, secret);
        }

        public static LoginUser getLoginUser(String token) {
            Claims body = Jwts.parser()
                    .setSigningKey(Base64UrlCodec.BASE64URL.encode(secret))
                    .parseClaimsJws(token).getBody();
            String data = (String) body.get(PAYLOAD_KEY);

            String[] decrypt = AES.decrypt(data, secret).split("#");
            if (log.isDebugEnabled()) {
                log.debug("解密前的数据：" + data);
                log.debug("解密后的数据：" + Arrays.asList(decrypt));
            }
            String userId = decrypt[0];
            List<String> roleKeyList = Arrays.asList(decrypt[1].split(","));
            List<String> permsList = Arrays.asList(decrypt[2].split(","));

            LoginUser loginUser = new LoginUser();
            loginUser.setPermsList(permsList);
            loginUser.setRoleKeyList(roleKeyList);
            User user = new User();
            user.setUserId(Long.valueOf(userId));
            loginUser.setUser(user);
            return loginUser;
        }
    }
}
